<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Crypt;
use Validator;
use Redis;
use App\Models\User;

class LoginController extends Controller
{
    public function login(Request $request){
        $validator = Validator::make($request->all(), [
                'unionid' => 'required',
                'openid' => 'required',
                'name' => 'required',
                'avatar' => 'required'
            ]);

        if ($validator->fails()) {
            return response()->json(['code'=>config('constants.API_PARAM_ERROR_CODE'),'message'=>$validator->errors()->first()]);
        }

		$unionid = $request->input('unionid');
		$openid = $request->input('openid');
		$name = $request->input('name');
		$avatar = $request->input('avatar');

        $input = [
            'openid' => $openid,
            'name' => $name,
            'avatar' => $avatar
        ];

        $userInfo = User::where('unionid',$unionid)->first();
        if($userInfo){
            $userInfo->update($input);
        }else{
            $userInfo = User::create($input);
            $userInfo->unionid = $unionid;
            $userInfo->save();
        }

    	$token = Crypt::encrypt(json_encode($userInfo));

        if(!$token){
            return response()->json(['code'=>config('constants.API_TOKEN_ERROR_CODE'),'message' => config('constants.API_TOKEN_ERROR')]);
        }

        //设置token有效期
        Redis::set('userId:'.$userInfo->id,time());
        Redis::expire('userId:'.$userInfo->id,config('constants.API_TOKEN_EXPIRE_TIME'));

        return response()->json(['code'=>config('constants.API_SUCCESS_CODE'),'message' => config('constants.API_SUCCESS'),'token'=>$token]);
    }




    

    public function test(){
        $token = 'eyJpdiI6InRnSjI1a29DSmw2WTBTUHpQeHZtbUE9PSIsInZhbHVlIjoiZ2NJNjZyUGhTc2l3cVNPTHM3cVFqSEh3YmVta3F4T2Vqa2pcL3VNczRZZW1WQ09GNEx4ZXVOdTNSWVZ0V1llRllKck5ac1NuTzhKd05lN004NjNscGY5bVcyU3p0NFJkU0taZ0JBYXRLWmhmU3BLWW1Oc3dQT3ptOUZDUU05WFd3elBMcDJYcmdtMEVqT21OWFl3WklrSXBzUmFSdEdHYktFM1BiZXlDQkl0QU1hUEYwYVVOcDFkXC9iN1VkSEZjWjFWZ2h1eitvdnQyeVo1RjFhQ2lFMVFWN2grTUdmMkdjcUdjUkc4bE16eXFZPSIsIm1hYyI6ImZjNGQyOTAyYzUxNjM4M2NiZDdlZTQ4Y2U5ZmVlY2YyY2Y5YmFlZTMzODc4YmJjYjFkZDY4NmE2M2QwZmMxODMifQ==';
        
        // $userInfo = json_decode(Crypt::decrypt($token));
        // 
        try{
            $userInfo = json_decode(Crypt::decrypt($token));
            // return $userInfo->id;
            if(Redis::get('userId:'.$userInfo->id)){
                //更新token有效期
                Redis::expire('userId:'.$userInfo->id,5);
                return $userInfo->id;
            }else{
                return "valid";
            }
            
        }catch(\Exception $e){
            return $e->getMessage();
        }
        // dd($result);
    }

    public function test2(){
        echo "123";
    }


}
